package com.dragon.mylibrary.dfu;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.dragon.blelibrary.bleutils.SharedPreferencesBle;

import com.dragon.blelibrary.events.BlePropertyObservable;
import com.dragon.mylibrary.manager.BleEvent;
import com.dragon.utilslibrary.AppConfig;
import com.dragon.utilslibrary.tools.LogUtils;
import com.dragon.utilslibrary.tools.SdkUtils;

import no.nordicsemi.android.dfu.DfuProgressListener;
import no.nordicsemi.android.dfu.DfuProgressListenerAdapter;
import no.nordicsemi.android.dfu.DfuServiceInitiator;
import no.nordicsemi.android.dfu.DfuServiceListenerHelper;


public class DfuUtil {
	private static String tag = "DfuUtil";
	private static DfuUtil instance;
	private static boolean isInit;
	public DfuUtil() {}
	public static DfuUtil getInstance(){
		if(instance == null){
			instance = new DfuUtil();
		}
		return instance;
	}
	/**
	 * 开始ota
	 * @param context
	 * @param mac
	 * @param bleName
	 * @param filePath
	 */
	public void startDfu(Context context, String mac, String bleName, String filePath){
		final DfuServiceInitiator starter = new DfuServiceInitiator(mac)
		.setDeviceName(bleName)
		.setKeepBond(false)
		.setForceDfu(false)
		.setPacketsReceiptNotificationsEnabled(false)
		.setPacketsReceiptNotificationsValue(DfuServiceInitiator.DEFAULT_PRN_VALUE)
		.setUnsafeExperimentalButtonlessServiceInSecureDfuEnabled(true);
		starter.setZip(null, filePath);
		starter.start(context, DfuService.class);
	}

	public void startDfu2(Context context, String mac, String bleName, String filePath){
		final DfuServiceInitiator starter = new DfuServiceInitiator(mac)
				.setDeviceName(bleName)
				.setKeepBond(false)
				.setForceDfu(false)
				.setPacketsReceiptNotificationsEnabled(false)
				.setPacketsReceiptNotificationsValue(DfuServiceInitiator.DEFAULT_PRN_VALUE)
				.setUnsafeExperimentalButtonlessServiceInSecureDfuEnabled(true);
		starter.setZip(Uri.parse(filePath), null);
		starter.start(context, DfuService.class);
	}
	/**
	 * 是否正在ota中
	 * @param context
	 * @return
	 */
	public boolean isDfuServiceRunning(Context context) {
		@SuppressLint("WrongConstant") final ActivityManager manager = (ActivityManager) context.getSystemService("activity");
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if (DfuService.class.getName().equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}
//	/**
//	 * 暂停
//	 * @param context
//	 */
//	public void pauseDFU(Context context){
//		final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
//		final Intent pauseAction = new Intent(DfuService.BROADCAST_ACTION);
//		pauseAction.putExtra(DfuService.EXTRA_ACTION, DfuService.ACTION_PAUSE);
//		manager.sendBroadcast(pauseAction);
//	}
//	/**
//	 * 恢复  与 暂停成对
//	 * @param context
//	 */
//	public void resumeDFU(Context context){
//		final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
//		final Intent pauseAction = new Intent(DfuService.BROADCAST_ACTION);
//		pauseAction.putExtra(DfuService.EXTRA_ACTION, DfuService.ACTION_RESUME);
//		manager.sendBroadcast(pauseAction);
//	}
//	/**
//	 * 停止, 与开始 成对
//	 * @param context
//	 */
//	public void stopDFU(Context context){
//		final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
//		final Intent pauseAction = new Intent(DfuService.BROADCAST_ACTION);
//		pauseAction.putExtra(DfuService.EXTRA_ACTION, DfuService.ACTION_ABORT);
//		manager.sendBroadcast(pauseAction);
//	}
	/**
	 * 初始化
	 * @param context
	 */
	public void init(Context context){
		if(!isInit){
			DfuServiceListenerHelper.registerProgressListener(context, mDfuProgressListener);
			isInit = true;
		}
		
	}
	/**
	 * 反初始化
	 * @param context
	 */
	public void onDestroy(Context context){
		if(isInit){
			DfuServiceListenerHelper.unregisterProgressListener(context, mDfuProgressListener);
		}
		isInit = false;
		instance = null;
	}
	private final DfuProgressListener mDfuProgressListener = new DfuProgressListenerAdapter() {
		@Override
		public void onDeviceConnecting(final String deviceAddress) {
			LogUtils.i(tag, "onDeviceConnecting " + deviceAddress);
		}

		@Override
		public void onDfuProcessStarting(final String deviceAddress) {
			LogUtils.i(tag, "onDfuProcessStarting");
//			BlePropertyObservable.getInstance().fireEvent(BleEvent.OTA_START, deviceAddress);
		}

		@Override
		public void onEnablingDfuMode(final String deviceAddress) {
			LogUtils.i(tag, "onEnablingDfuMode");
		}

		@Override
		public void onFirmwareValidating(final String deviceAddress) {
			LogUtils.i(tag, "onFirmwareValidating");
		}

		@Override
		public void onDeviceDisconnecting(final String deviceAddress) {
			LogUtils.i(tag, "onDeviceDisconnecting");
		}

		@Override
		public void onDfuCompleted(final String deviceAddress) {
			LogUtils.i(tag, "onDfuCompleted");
			SharedPreferencesBle.setSharedStringData(AppConfig.mContext, SharedPreferencesBle.BLE_MAC, SdkUtils.macMinus(deviceAddress, 1).toUpperCase());
//			BlePropertyObservable.getInstance().fireEvent(BleEvent.OTA_END, SdkUtils.macMinus(deviceAddress, 1).toUpperCase());
		}

		@Override
		public void onDfuAborted(final String deviceAddress) {
			LogUtils.i(tag, "onDfuAborted");
		}

		@Override
		public void onProgressChanged(final String deviceAddress, final int percent, final float speed, final float avgSpeed, final int currentPart, final int partsTotal) {
			LogUtils.i(tag, "onProgressChanged + " + percent + " speed = " + speed + " avgSpeed = " +avgSpeed + " partsTotal = " + partsTotal);
//			ShowLog.getInstance().setText(deviceAddress, "percent = " + percent );
//			BlePropertyObservable.getInstance().fireEvent(BleEvent.OTA_Progress, SdkUtils.macMinus(deviceAddress, 1).toUpperCase(),percent);
		}

		@Override
		public void onError(final String deviceAddress, final int error, final int errorType, final String message) {
			LogUtils.i(tag, "onError");
//			BlePropertyObservable.getInstance().fireEvent(BleEvent.OTA_ERROR, deviceAddress,error,errorType,message);
		}
	};
}
